﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using PlcServer;
using Server;
namespace WindowsFormsApp1
{
    public partial class Form1 : Form, INotifyPropertyChanged
    {
        internal List<Tag> Tags { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public void Set<T>(ref T oldVal, T newVal, [CallerMemberName] string name = "")
        {
            if (!EqualityComparer<T>.Default.Equals(oldVal, newVal))
            {
                oldVal = newVal;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
        public Form1()
        {
            InitializeComponent();
        }

        PlcHelper PlcTag = new PlcHelper();
        private void button1_Click(object sender, EventArgs e)
        {
            var str = AppDomain.CurrentDomain.BaseDirectory;
            PlcHelper.InitPlc();
            PlcHelper.PushTagValEvent += PlcHelper_PushTagValEvent;
        }

        private void PlcHelper_PushTagValEvent(string arg1, int arg2)
        {
            FreshTag();
        }

        private void FreshTag()
        {
            Task.Run(() =>
            {
                int valComm = PlcHelper.GetTagValInt("Trigger").Content;
                Thread.Sleep(300);
                Tags = new List<Tag>();
                Tags.Add(new Tag() { No = "Trigger", Value = PlcTag["Trigger"].ToString() });
                Tags.Add(new Tag() { No = "CMD", Value = PlcTag["CMD"].ToString() });
                Tags.Add(new Tag() { No = "BearingNo", Value = PlcTag["BearingNo"].ToString() });
                Tags.Add(new Tag() { No = "OilNum", Value = PlcHelper.GetValFloatInTime("OilNum").Content.ToString("F") });
                if (this.IsHandleCreated)
                {
                    BeginInvoke(new Action(() =>
                    {
                        dataGridView1.DataSource = Tags;
                    }));
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            PlcHelper.SetTagInt16("Trigger", 1);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            PlcHelper.SetTagInt16("BearingNo", Int16.Parse(textBox1.Text));
            FreshTag();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            PlcHelper.SetTagFloat("OilNum", float.Parse(textBox2.Text));
            FreshTag();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            PlcHelper.SetTagInt16("Trigger", 0);
        }
    }

    class Tag
    {
        public string No { get; set; }
        public string Value { get; set; }

    }
}
